package com.example.dasilianxi.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;


import com.example.dasilianxi.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class SignatureView extends View {
    public static final String TAG = "asdf";
    private Path mPath = new Path();
    private Paint mPaint = new Paint();
    //位图的绘制内容输出者：画布
    private Canvas mCanvas;
    //用来存放绘制内容的位图
    private Bitmap mCacheBitmap;
    //上下文
    private Context mContext;

    public SignatureView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(10);
        mPaint.setColor(getResources().getColor(R.color.red, null));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mCacheBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mCacheBitmap);
        mCanvas.drawColor(Color.WHITE);
        // 重置路径，以便新的绘制不会与旧的绘制重叠
        mPath.reset();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        final int pointerCount = event.getPointerCount();
        for (int i = 0; i < pointerCount; i++) {
            switch (event.getActionMasked()) {
                case MotionEvent.ACTION_DOWN:
                case MotionEvent.ACTION_POINTER_DOWN:
                    // 当新的手指触摸屏幕时，为这个手指创建一个新的路径，并移动到它的位置
                    if (mPaths.size() <= i) {
                        mPaths.add(new Path());
                    }
                    mPaths.get(i).moveTo(event.getX(i), event.getY(i));
                    break;
                case MotionEvent.ACTION_MOVE:
                    // 移动时，为每个手指更新路径
                    for (int j = 0; j < pointerCount; j++) {
                        if (mPaths.size() > j) {
                            mPaths.get(j).lineTo(event.getX(j), event.getY(j));
                        }
                    }
                    invalidate(); // 重绘界面
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_POINTER_UP:
                    // 当手指抬起时，不需要做任何操作，因为我们希望保留签名
                    break;
            }
        }
        // 将所有路径绘制到画布上
        for (Path path : mPaths) {
            mCanvas.drawPath(path, mPaint);
        }
        return true;
    }



    // 在类的成员变量中添加一个路径列表来存储每个手指的路径
    private List<Path> mPaths = new ArrayList<>();


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.e(TAG, "onDraw canvas = " + canvas);

        // 将位图绘制到 View 的 Canvas 上，这样 View 上就会显示绘制的内容
        canvas.drawBitmap(mCacheBitmap, 0, 0, null);
    }

    /**
     * 清空
     */
    public void clear() {
        Log.e(TAG, "clear()");
        if (mPath != null) {
            Log.e(TAG, "before clear mPath isEmpty => " + mPath.isEmpty());
            mPath.reset();
            mCanvas.drawColor(Color.WHITE);
            Log.e(TAG, "after clear mPath isEmpty => " + mPath.isEmpty());
            invalidate();
        }
    }

    public void save() {
        //创建一个文件用于存放图片
        File file = new File(mContext.getExternalFilesDir(null) + "testSign.png");
        if (file.exists()) {
            file.delete();
        }
        OutputStream outputStream = null;
        try {
            //输出到这个文件
            outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(mContext, "保存异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        //压缩形成输出流
        mCacheBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        Toast.makeText(mContext, "保存成功!path:" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
    }

    public void saveImageToGallery() {
        String savedImageURL = MediaStore.Images.Media.insertImage(
                mContext.getContentResolver(),
                mCacheBitmap,
                "testSign",
                "testSign save"
        );
        Toast.makeText(mContext, "保存成功! URL:" + savedImageURL, Toast.LENGTH_SHORT).show();
    }
}
